/*
 * $Id: LogEventReceiver.java 22 2014-10-08 07:56:19Z ratking $
 *
 * Copyleft (C) 2014 RatKing. All wrongs reserved.
 */
package cn.ratking.demo.jaws7.jms;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.inject.Inject;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.slf4j.Logger;

import cn.ratking.demo.jaws7.model.LogEvent;
import cn.ratking.demo.jaws7.system.service.LogEventService;

/**
 * 日志事件的JMS消息接收者
 *
 * @see http://docs.oracle.com/javaee/7/tutorial/doc/jms-concepts005.htm#BNCGQ
 */
@MessageDriven(activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "jms/LogEventQueue"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
//@MessageDriven(mappedName = "jms/LogEventQueue")
public class LogEventReceiver implements MessageListener {

    @Inject
    private transient Logger log;
    @Inject
    private LogEventService logEventService;
    @Resource
    private MessageDrivenContext mdc;

    /** 无参构造方法 */
    public LogEventReceiver() {
    }

    /**
     * 接收并处理JMS消息事件
     *
     * @param message JMS消息
     */
    @Override
    public void onMessage(Message message) {
        log.debug("Debug: LogEventReceiver.onMessage()");
        try {
            if (message.isBodyAssignableTo(LogEvent.class)) {
                LogEvent logEvent = message.getBody(LogEvent.class);
                logEventService.create(logEvent);
                log.debug("接收并处理日志事件的JMS消息成功：logEvent=" + logEvent);
            } else {
                log.warn("接收到的JMS消息类型不是日志事件，已被丢弃：message=" + message);
            }
        } catch (JMSException ex) {
            log.error("接收并处理日志事件的JMS消息异常：" + ex.getMessage(), ex);
            mdc.setRollbackOnly();
        } // try-catch
    }
}
